﻿/*
 * KLF Headless Browser
 * Written by Kris Oye <kristianoye@gmail.com>
 * Copyright (C) 2011-2012.  All rights reserved.
 */
namespace KLF.Lib.Browser.JavascriptHelpers
{
    #region Using Statements

    using System;
    using System.Net;
    using System.Linq;
    using System.Collections.Generic;

    #endregion

    public class History
    {
        #region Properties

        public List<Uri> HistoryList { get; protected set; }

        public BrowserWindow Window { get; protected set; }

        public int length { get { return HistoryList.Count; } }

        #endregion

        #region Constructors

        public History(BrowserWindow window)
        {
            HistoryList = new List<Uri>();
            Window = window;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Navigates to the previous location.
        /// </summary>
        public void back()
        {
            int currentIndex = HistoryList.IndexOf(Window.Location);

            if (currentIndex > 0)
            {
                RequestContext context = new RequestContext(Window, HistoryList[currentIndex - 1]) { FromHistory = true };

                Window.GoTo(context);
            }
        }

        /// <summary>
        /// Navigates to the next most recent location.
        /// </summary>
        public void forward()
        {
            int currentIndex = HistoryList.IndexOf(Window.Location);

            if ((currentIndex > -1) && (currentIndex + 1 < HistoryList.Count))
            {
                RequestContext context = new RequestContext(Window, HistoryList[currentIndex - 1]) { FromHistory = true };

                Window.GoTo(context);
            }
        }

        /// <summary>
        /// Navigates to a point in history using either a numeric reference 
        /// (+2, -2, 2) or a URL from the history.
        /// </summary>
        /// <param name="param"></param>
        public void go(string param)
        {
            int tmpValue;

            if (Int32.TryParse(param, out tmpValue))
            {
                int currentIndex = HistoryList.IndexOf(Window.Location);

                if (currentIndex > -1)
                {
                    int newIndex = currentIndex + tmpValue;

                    if (newIndex > -1 && newIndex < HistoryList.Count)
                    {
                        RequestContext context = new RequestContext(Window, HistoryList[newIndex]) { FromHistory = true };

                        Window.GoTo(context);
                    }
                }
            }
            else
            {
            }
        }

        public void go(int param)
        {
            go(param.ToString());
        }

        #endregion
    }
}
